package cn.rokhdelar.ams.config.exception;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 这个异常用于在web端接口和安卓端接口都用到了的情景,后续捕获处理,以便返回不同结果
     * @param request
     * @param exception
     */
    @ExceptionHandler(value = MixNoHandException.class)
    public void  MixNoHandExceptionHandler(HttpServletRequest request, MixNoHandException exception) {
        log.error("Url:{}, Method: {}. Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);
        throw exception;
    }
    @ExceptionHandler(value = VerifyCaptchaException.class)
    public ResponseEntity<String> captchaExceptionHandler(HttpServletRequest request, VerifyCaptchaException exception) {
        log.error("Url:{}, Method: {}. Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("图像验证错误：" + exception.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exceptionHandler(HttpServletRequest request, Exception exception) {
        log.error("Url:{}, Method: {}.Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误，请联系管理员。");
    }

    /**
     * 运行时错误处理函数
     */
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity<String> runtimeExceptionHandler(HttpServletRequest request, RuntimeException exception) {
        log.error("Url:{}, Method: {}. Controller called error in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误：" + exception.getMessage());
    }

    /**
     * 参数校校验异常处理程序
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<String> methodArgumentNotValidExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException exception) {
        log.error("Url:{}, Method: {}. Controller called error! Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);

        StringBuilder sb = new StringBuilder();
        exception.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String message = error.getDefaultMessage();
            sb.append(fieldName).append(":").append(message).append(";");
        });
        log.error(sb.toString());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("参数校验失败，请检查后再试。");
    }

    /**
     * 认证凭据异常处理程序
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public ResponseEntity<String> credentialsExceptionHandler(HttpServletRequest request, BadCredentialsException exception) {
        log.error("Url:{}, Method: {}. Controller called error! Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("用户名和密码不正确，请检查后再试。");
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(value = BusException.class)
    public ResponseEntity<String> busExceptionHandler(HttpServletRequest request, BusException exception) {
        log.error("Url:{}, Method: {}. Controller called error! Catch in ErrorHandler", request.getRequestURI(),
                request.getMethod(), exception);
//        return ResponseEntity.status(601).body(new BusinessExceptionResult(exception.getMessage()));
        return ResponseEntity.status(601).body(exception.getMessage());

    }

}
